/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package rs_GUI;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.DefaultListModel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import pojos.*;


/**
 *
 * @author Mastroperrou
 */

public class MusicGroup_MainPanel extends javax.swing.JPanel {
    
    RadioStationParentFrame frame;
    EntityManager em;
    private Musicgroup mgroupBackup;
    private Musicgroup mgroup = new Musicgroup(); 
    private char modStatus;
    private List<Musicgroup> groupList = new ArrayList<>(0);
    private TableModel model = new DefaultTableModel();
    
    JMenuBar menu = new JMenuBar();
    JMenu  jMenu1 = new JMenu("Μενού");  
    
    /**
     * Creates new form WelcomeJPanel
     */
    public MusicGroup_MainPanel(RadioStationParentFrame frame) {
      
        this.frame = frame;
        this.em = frame.getEm();
        initComponents();
        
        //Απενεργοποίηση των πεδίων εισαγωγής στοιχείων και των labels τους
        groupTable.setRowSelectionInterval(0, 0);
        groupNameTextField.setEnabled(false);
        groupNameLabel.setEnabled(false);
        formationDateDateChooser.setEnabled(false);
        formationDateLabel.setEnabled(false);
        artistListLabel.setEnabled(false);
        artistTable.setEnabled(false);
        addArtistButton.setEnabled(false);
        removeArtistButton.setEnabled(false);
        addArtistButton.setVisible(false);
        removeArtistButton.setVisible(false);        
        availArtistLabel.setEnabled(false);
        availArtistTable.setEnabled(false);
        saveButton.setEnabled(false);
        saveButton.setVisible(false);
        cancelButton.setEnabled(false);
        cancelButton.setVisible(false);
        availArtistLabel.setVisible(false);
        availArtistTable.setVisible(false);
        jScrollPane2.setVisible(false);
        
        
        this.groupTable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
          
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (groupTable.getSelectedRow()!= -1){
                mgroup = musicgroupList.get(groupTable.convertRowIndexToModel(groupTable.getSelectedRow()));                              
                repaintTables(mgroup);
                }
            }
        });
        
                
        JMenuItem newGroupItem = new JMenuItem("Εισαγωγή Νέου");
        newGroupItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newGroupItemActionPerformed(evt);
            }
        });
        jMenu1.add(newGroupItem);
              
        JMenuItem exitItem = new JMenuItem("Έξοδος");
        exitItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitItemActionPerformed(evt);
            }
        });
        jMenu1.add(exitItem);
               
        menu.add(jMenu1);
        frame.setJMenuBar(menu);

        groupTable.clearSelection();

    }
    
    private void setSaveMenu(){
        jMenu1 = new JMenu("Μενού");
        menu = new JMenuBar();
        
        JMenuItem saveGroupItem = new JMenuItem("Αποθήκευση");
        saveGroupItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveGroupItemActionPerformed(evt);
            }
        });
        jMenu1.add(saveGroupItem);
              
        JMenuItem cancelItem = new JMenuItem("Ακύρωση");
        cancelItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelItemActionPerformed(evt);
            }
        });
        jMenu1.add(cancelItem);
               
        menu.add(jMenu1);
        frame.setJMenuBar(menu);        
    }
    
    private void saveGroupItemActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.saveButtonActionPerformed(evt);
    }      
     
    private void cancelItemActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.cancelButtonActionPerformed(evt);
    }
    
    private void newGroupItemActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.newButtonActionPerformed(evt);
    }      
     
    private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.exitButtonActionPerformed(evt);
    } 
    
    public List<Artist> getAvailArtist(Musicgroup msg) {
        List<Artist> artList = new ArrayList<>(0);
        if (msg.getId()==null) {
            //JOptionPane.showMessageDialog(this, "Το αντικείμενο δεν υπάρχει στην βάση...");
            return artList;
        }
        Query q = em.createNativeQuery("SELECT * FROM ARTIST a WHERE ID NOT IN "
                            + "(SELECT ARTISTID FROM ARTIST_MUSICGROUP WHERE MUSICGROUPID = "
                            +    msg.getId().toString() +")", Artist.class);

            if (!em.getTransaction().isActive()) {
                    em.getTransaction().begin();
            } 

            try {
               artList =  q.getResultList();
            } catch (Exception e) {
                e.printStackTrace();
                em.getTransaction().rollback();
            }                 
        
        return artList;
    }
    
    private void repaintTables(Musicgroup msg){
        List<Artist> temp = artistQuery1.getResultList();
        temp.removeAll(msg.getArtistList());
        artistList.clear();
        artistList.addAll(mgroup.getArtistList());
        artistList1.clear();
        artistList1.addAll(temp);
        //JOptionPane.showMessageDialog(null, msg.getId());
        List<Artist> artList = getAvailArtist(msg);
        DefaultListModel<Artist> model = new DefaultListModel();
        for (Artist art : artList) {
            model.addElement(art);
        }
        availArtistTable.setModel(model);
        jScrollPane4.validate();
        jScrollPane4.repaint();
        jScrollPane4.doLayout(); 
        artistTable.repaint();
        availArtistTable.repaint();        
        artistTable.clearSelection();
        availArtistTable.clearSelection();
            
    }
            
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        musicgroupQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT m FROM Musicgroup m");
        musicgroupList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : musicgroupQuery.getResultList();
        artistQuery1 = em.createQuery("SELECT a FROM Artist a");
        artistList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : artistQuery1.getResultList();
        artistQuery = em.createQuery("SELECT a FROM Artist a");
        artistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : artistQuery.getResultList();
        jLabel7 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        groupTable = new javax.swing.JTable();
        newButton = new javax.swing.JButton();
        changeButton = new javax.swing.JButton();
        deleteButton1 = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        groupNameTextField = new javax.swing.JTextField();
        formationDateLabel = new javax.swing.JLabel();
        groupNameLabel = new javax.swing.JLabel();
        formationDateDateChooser = new com.toedter.calendar.JDateChooser();
        artistListLabel = new javax.swing.JLabel();
        availArtistLabel = new javax.swing.JLabel();
        addArtistButton = new javax.swing.JButton();
        removeArtistButton = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        artistTable = new javax.swing.JTable();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        availArtistTable = new javax.swing.JList();

        setMaximumSize(new java.awt.Dimension(610, 445));
        setMinimumSize(new java.awt.Dimension(610, 445));
        setPreferredSize(new java.awt.Dimension(610, 445));

        jLabel7.setText("ΠΙΝΑΚΑΣ ΣΥΓΚΡΟΤΗΜΑΤΩΝ");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Λίστα συγκροτημάτων"));

        groupTable.setFont(new java.awt.Font("Comic Sans MS", 1, 13)); // NOI18N
        groupTable.setForeground(new java.awt.Color(51, 51, 51));
        groupTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, musicgroupList, groupTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        groupTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                groupTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(groupTable);

        newButton.setText("ΕΙΣΑΓΩΓΗ ΝΕΟΥ");
        newButton.setMaximumSize(new java.awt.Dimension(113, 35));
        newButton.setMinimumSize(new java.awt.Dimension(113, 35));
        newButton.setPreferredSize(new java.awt.Dimension(113, 35));
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newButtonActionPerformed(evt);
            }
        });

        changeButton.setText("ΜΕΤΑΒΟΛΗ");
        changeButton.setMaximumSize(new java.awt.Dimension(113, 35));
        changeButton.setMinimumSize(new java.awt.Dimension(113, 35));
        changeButton.setPreferredSize(new java.awt.Dimension(113, 35));
        changeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeButtonActionPerformed(evt);
            }
        });

        deleteButton1.setText("ΔΙΑΓΡΑΦΗ");
        deleteButton1.setMaximumSize(new java.awt.Dimension(113, 35));
        deleteButton1.setMinimumSize(new java.awt.Dimension(113, 35));
        deleteButton1.setPreferredSize(new java.awt.Dimension(113, 35));
        deleteButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButton1ActionPerformed(evt);
            }
        });

        exitButton.setText("ΕΞΟΔΟΣ");
        exitButton.setMaximumSize(new java.awt.Dimension(113, 35));
        exitButton.setMinimumSize(new java.awt.Dimension(113, 35));
        exitButton.setPreferredSize(new java.awt.Dimension(113, 35));
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(changeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(deleteButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {changeButton, deleteButton1, exitButton, newButton});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(changeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deleteButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {changeButton, deleteButton1, exitButton, newButton});

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Λεπτομέρειες"));
        jPanel2.setMaximumSize(new java.awt.Dimension(368, 324));
        jPanel2.setMinimumSize(new java.awt.Dimension(368, 324));
        jPanel2.setPreferredSize(new java.awt.Dimension(368, 324));

        formationDateLabel.setText("Ημ.Δημιουργίας:");

        groupNameLabel.setText("Επωνυμία Συγκ/τος:");

        artistListLabel.setText("Λίστα Καλλιτεχνών:");

        availArtistLabel.setText("Διαθέσιμοι Καλλιτέχνες:");

        addArtistButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/misc/1uparrow.png"))); // NOI18N
        addArtistButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addArtistButtonActionPerformed(evt);
            }
        });

        removeArtistButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/misc/1downarrow.png"))); // NOI18N
        removeArtistButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeArtistButtonActionPerformed(evt);
            }
        });

        jScrollPane4.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        artistTable.setColumnSelectionAllowed(true);
        artistTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, artistList, artistTable);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artisticname}"));
        columnBinding.setColumnName("Καλλιτεχνικό Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        artistTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                artistTableMouseClicked(evt);
            }
        });
        jScrollPane4.setViewportView(artistTable);
        artistTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        saveButton.setLabel("ΑΠΟΘΗΚΕΥΣΗ");
        saveButton.setMaximumSize(new java.awt.Dimension(120, 23));
        saveButton.setMinimumSize(new java.awt.Dimension(120, 23));
        saveButton.setPreferredSize(new java.awt.Dimension(120, 23));
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setLabel("ΑΚΥΡΩΣΗ");
        cancelButton.setMaximumSize(new java.awt.Dimension(120, 23));
        cancelButton.setMinimumSize(new java.awt.Dimension(120, 23));
        cancelButton.setPreferredSize(new java.awt.Dimension(120, 23));
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, artistList1, availArtistTable);
        bindingGroup.addBinding(jListBinding);

        availArtistTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                availArtistTableMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(availArtistTable);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(70, 70, 70)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(118, 118, 118)
                        .addComponent(removeArtistButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(addArtistButton)
                        .addGap(118, 118, 118))))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(formationDateLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(groupNameLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(15, 15, 15)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(groupNameTextField)
                            .addComponent(formationDateDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)))
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(artistListLabel)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(availArtistLabel))
                .addGap(65, 65, 65))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {addArtistButton, removeArtistButton});

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, saveButton});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(groupNameLabel)
                    .addComponent(groupNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(formationDateLabel)
                    .addComponent(formationDateDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(artistListLabel)
                .addGap(5, 5, 5)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addArtistButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(removeArtistButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(availArtistLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {addArtistButton, removeArtistButton});

        jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {cancelButton, saveButton});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel7)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void deleteButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButton1ActionPerformed
        if (groupTable.getSelectedRow() != -1 ) { //Ean yparxoyn epilegmenes grammes

                mgroup = musicgroupList.get(groupTable.convertRowIndexToModel(groupTable.getSelectedRow()));        
                
                // Ελέγχουμε αν το συγκεκριμένο group είναι 
                //ο μόναδικός ερμηνευτής σε κάποιο Album 
                for (Album alb : mgroup.getAlbumList()) {
                    if (alb.getArtistid() == null) {
                        JOptionPane.showMessageDialog(this, 
                                "Το Group είναι ο μοναδικός συντελεστής σε κάποιο/α Άλμπουμ\n" 
                                + "και δεν μπορεί να διαγραφεί", 
                                "Σφάλμα",
                                JOptionPane.WARNING_MESSAGE);
                        //deleteButton.setEnabled(true);
                        return;      
                    }
                }
        if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
        }
       // JOptionPane.showMessageDialog(this,"Row" + groupTable.getSelectedRow());
        

            try {   
                    
                    for (Artist  art : mgroup.getArtistList()){  // gia kathe kallitexnh pou ton afora
                        art.getMusicgroupList().remove(mgroup);
                        em.merge(art);                        
                    }
                    
                    for (Album album : mgroup.getAlbumList()) {
                        album.setMusicgroupid(null);
                        em.remove(em.find(Album.class, album.getId()));
                    }
                    
                  mgroup.getArtistList().clear();
                  mgroup.getAlbumList().clear();
                  em.merge(mgroup);
                  em.remove(em.find(Musicgroup.class, mgroup.getId())); //diagrapse to kallitexnh
                  musicgroupList.remove(mgroup); // bgale apo ton pinaka ta diagegrammena sygkrothmata                  
                  
            } catch (Exception e) {
                e.printStackTrace();
                em.getTransaction().rollback();
            }  
        } else {
            JOptionPane.showMessageDialog(this,"Επιλέξτε Συγκρότημα...");
            groupTable.clearSelection();
            return;            
        } 
        
        saveButton.setEnabled(true);
        saveButton.setVisible(true);
        cancelButton.setEnabled(true);
        cancelButton.setVisible(true);
        setSaveMenu();
       // JOptionPane.showMessageDialog(this,"List" + musicgroupList.size());
        if (!musicgroupList.isEmpty()) {
           groupTable.clearSelection(); 
        } else {
           this.deleteButton1.setEnabled(false);
        }
            groupTable.updateUI();
            modStatus = 'D';
        
    }//GEN-LAST:event_deleteButton1ActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed

            frame.addPanelInMain(new EmptyMainPanel(frame));
            frame.addPanelInSide(new MainMenuSidePanel(frame,em));
            
    }//GEN-LAST:event_exitButtonActionPerformed

    private void changeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeButtonActionPerformed

        if ((groupTable.getSelectedRow() == -1) || musicgroupList.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Επιλέξτε συγκρότημα!");
            groupTable.clearSelection();
        } else {
            if (groupTable.getSelectedRowCount()>1) {
                JOptionPane.showMessageDialog(this, "Επιλέξτε 1 συγκρότημα!");
            } else {
                
                groupNameTextField.setEnabled(true);
                groupNameLabel.setEnabled(true);
                formationDateDateChooser.setEnabled(true);
                formationDateDateChooser.repaint();
                formationDateDateChooser.updateUI();
                formationDateLabel.setEnabled(true);
                artistListLabel.setEnabled(true);
                artistTable.setEnabled(true);
                addArtistButton.setEnabled(true);
                removeArtistButton.setEnabled(true);
                addArtistButton.setVisible(true);
                removeArtistButton.setVisible(true);                 
                availArtistLabel.setEnabled(true);
                availArtistTable.setEnabled(true);
                availArtistLabel.setVisible(true);
                availArtistTable.setVisible(true);
                jScrollPane2.setVisible(true);
                saveButton.setEnabled(true);
                saveButton.setVisible(true);
                cancelButton.setEnabled(true);
                cancelButton.setVisible(true); 
                groupTable.setEnabled(false);                
                this.exitButton.setEnabled(false);
                this.deleteButton1.setEnabled(false);
                this.newButton.setEnabled(false);
                this.changeButton.setEnabled(false);
                groupNameTextField.requestFocus();                
                mgroup = musicgroupList.get(groupTable.convertRowIndexToModel(groupTable.getSelectedRow()));
                mgroupBackup = new Musicgroup();
                mgroupBackup.setAlbumList(mgroup.getAlbumList());
                mgroupBackup.setArtistList(mgroup.getArtistList());
                mgroupBackup.setFormationdate(mgroup.getFormationdate());
                mgroupBackup.setId(mgroup.getId());
                mgroupBackup.setName(mgroup.getName());                
                this.groupNameTextField.setText(mgroup.getName());
                this.formationDateDateChooser.setDate(mgroup.getFormationdate());
                //JOptionPane.showMessageDialog(null, mgroup.getId());
                this.repaintTables(mgroup);
                setSaveMenu();
                modStatus = 'M';              
            }
        }
    }//GEN-LAST:event_changeButtonActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        groupNameTextField.setEnabled(true);
        groupNameLabel.setEnabled(true);
        formationDateDateChooser.setEnabled(true);
        formationDateLabel.setEnabled(true);
        artistListLabel.setEnabled(true);
        availArtistLabel.setEnabled(true);
        availArtistTable.setEnabled(true);
        availArtistLabel.setVisible(true);
        availArtistTable.setVisible(true);
        jScrollPane2.setVisible(true);
        addArtistButton.setEnabled(true);
        removeArtistButton.setEnabled(true);
        addArtistButton.setVisible(true);
        removeArtistButton.setVisible(true); 
        artistTable.setEnabled(true);
        saveButton.setEnabled(true);
        saveButton.setVisible(true);
        cancelButton.setEnabled(true);
        cancelButton.setVisible(true);
        mgroup = new Musicgroup(null,"");
        mgroup.setAlbumList(new ArrayList<Album>(0));
        mgroup.setArtistList(new ArrayList<Artist>(0)); 
        if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
        }  
        if (em.getTransaction().isActive()) {
                try {
                    em.persist(mgroup);                    
                    em.flush(); //entolh gia na adeiasoume ton persistent buffer sthn bash kai na paroume ID uncommited.
                } catch (Exception e) {
                e.printStackTrace();
                em.getTransaction().rollback();
            }
        } 
        this.repaintTables(mgroup);
        groupTable.setEnabled(false);
        this.exitButton.setEnabled(false);
        this.deleteButton1.setEnabled(false);
        this.newButton.setEnabled(false);
        this.changeButton.setEnabled(false);
        groupNameTextField.requestFocus();
        setSaveMenu();
        modStatus = 'I';
    }//GEN-LAST:event_newButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
        }
        if (modStatus=='D') {
            Object[] options = {"Ναι","Οχι"};
            Integer choice = JOptionPane.showOptionDialog(frame,
            "Επιβεβαίωση Διαγραφής;",
            null,
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[0]);

            if (choice == JOptionPane.YES_OPTION){
                if (em.getTransaction().isActive()) {
                    try {
                        em.getTransaction().commit();
                        this.saveButton.setEnabled(false);
                    } catch (Exception e) {
                            e.printStackTrace();
                        em.getTransaction().rollback(); 
                    }
                }
            }
            frame.addPanelInMain(new MusicGroup_MainPanel(frame));
        } else if (modStatus=='M') {

            mgroup.setName(this.groupNameTextField.getText());
            mgroup.setFormationdate(this.formationDateDateChooser.getDate());
            
            if (mgroup.getArtistList().size()<2) {
                JOptionPane.showMessageDialog(frame,"Το συγκρότημα έχει λιγότερους από 2 καλλιτέχνες");
                return;
            }
            
            if (mgroup.getName().length()<1) {
                JOptionPane.showMessageDialog(frame,"Μη αποδεκτό όνομα..");
                this.groupNameTextField.requestFocus();
                return;
            }
            
            List<Musicgroup> groups = new ArrayList<>(0);
            for (Musicgroup msg : this.musicgroupList) {
                groups.add(msg);
            }
            groups.remove(mgroupBackup);
            
            List<String> names = new ArrayList<>(0);
            for (Musicgroup msg : groups) {
                names.add(msg.getName());
            }
                      
            if (names.contains(mgroup.getName())) {
                JOptionPane.showMessageDialog(frame,"Το όνομα υπάρχει ήδη...");
                this.groupNameTextField.requestFocus();                    
                return;
            }  
            
            Object[] options = {"Ναι","Οχι"};
            Integer choice = JOptionPane.showOptionDialog(frame,
            "Επιβεβαίωση αλλαγών;",
            null,
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[0]);
            
   
            if (choice == JOptionPane.YES_OPTION){
                if (em.getTransaction().isActive()) {
                    try {
                        em.merge(mgroup);
                        em.getTransaction().commit();
                        this.saveButton.setEnabled(false);
                    } catch (Exception e) {
                            e.printStackTrace();
                        em.getTransaction().rollback(); 
                    }
                }
            } 
            frame.addPanelInMain(new MusicGroup_MainPanel(frame));
        } else if (modStatus=='I') {
            
            mgroup.setName(this.groupNameTextField.getText());
            mgroup.setFormationdate(this.formationDateDateChooser.getDate());
            
            if (mgroup.getArtistList().size()<2) {
                JOptionPane.showMessageDialog(frame,"Το συγκρότημα έχει λιγότερους από 2 καλλιτέχνες");
                this.availArtistTable.requestFocus();
                return;
            }

            if (mgroup.getName().length()<1) {
                JOptionPane.showMessageDialog(frame,"Μη αποδεκτό όνομα..");
                this.groupNameTextField.requestFocus();
                return;
            }
            
            List<String> names = new ArrayList<>(0);
            for (Musicgroup msg : this.musicgroupList) {
                names.add(msg.getName());
            }
                      
            if (names.contains(mgroup.getName())) {
                JOptionPane.showMessageDialog(frame,"Το όνομα υπάρχει ήδη...");
                this.groupNameTextField.requestFocus();                    
                return;
            }  
            Object[] options = {"Ναι","Οχι"};
            Integer choice = JOptionPane.showOptionDialog(frame,
            "Επιβεβαίωση στοιχείων;",
            null,
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[0]);
                       
           
            if (choice == JOptionPane.YES_OPTION){
                if (em.getTransaction().isActive()) {
                    try {
                        em.merge(mgroup);
                        em.getTransaction().commit();
                        this.saveButton.setEnabled(false);
                    } catch (Exception e) {
                        e.printStackTrace();
                        em.getTransaction().rollback(); 
                    }
                }
            } else {
               return;
            } 
            frame.addPanelInMain(new MusicGroup_MainPanel(frame));
        }
        
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed

            Object[] options = {"Ναι","Οχι"};
            Integer choice = JOptionPane.showOptionDialog(frame,
            "Όλες οι αλλαγές θα χαθούν!",
            null,
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[0]);

            if (choice == JOptionPane.YES_OPTION){
                if (em.getTransaction().isActive()) {
                    try {
                        em.getTransaction().rollback();
                        this.saveButton.setEnabled(false);
                    } catch (Exception e) {
                            e.printStackTrace();
                        em.getTransaction().rollback(); 
                    }
                }
            } 
            else {
                this.groupNameTextField.requestFocus();
                return;
            }
            frame.addPanelInMain(new MusicGroup_MainPanel(frame)); 
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void addArtistButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistButtonActionPerformed
        Integer avLstPos = availArtistTable.getSelectedIndex();
        
        if (avLstPos == -1) {
            JOptionPane.showMessageDialog(this,"Επιλέξτε καλλιτέχνη...");
            this.availArtistTable.requestFocus();
            return;
        }
  
        Artist art = (Artist)availArtistTable.getSelectedValue();
        
        art.getMusicgroupList().add(mgroup);
        mgroup.getArtistList().add(art);
        if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
        }         
        if (em.getTransaction().isActive()) {
                try {

                    em.merge(art);
                    em.merge(mgroup);
                    em.flush(); 

                } catch (Exception e) {
                e.printStackTrace();
                em.getTransaction().rollback();
            }
        }
        repaintTables(mgroup);
                                   
    }//GEN-LAST:event_addArtistButtonActionPerformed

    private void removeArtistButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeArtistButtonActionPerformed
        Integer lstPos = artistTable.getSelectedRow();
        
        if (lstPos == -1 || modStatus=='I' ) {
            JOptionPane.showMessageDialog(this,"Επιλέξτε καλλιτέχνη...");
            artistTable.requestFocus();
            return;
        }           
            Artist art =  artistList.get(artistTable.convertRowIndexToModel(lstPos));
      
            art.getMusicgroupList().remove(mgroup);
            mgroup.getArtistList().remove(art);
            
        if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
        }         
        if (em.getTransaction().isActive()) {
                    try {
                        em.merge(art);                        
                        em.merge(mgroup);
                        em.flush(); 
                                               
                        // musicgroupList.indexOf(msg)
                                                                      
                    } catch (Exception e) {
                    e.printStackTrace();
                    em.getTransaction().rollback();
                }
            }            
        repaintTables(mgroup);
    }//GEN-LAST:event_removeArtistButtonActionPerformed

    private void groupTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_groupTableMouseClicked
        if(evt.getClickCount()==2){
            ActionEvent e = null;
            changeButtonActionPerformed(e);
        }
    }//GEN-LAST:event_groupTableMouseClicked

    private void artistTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_artistTableMouseClicked
        if(evt.getClickCount()==2){
            ActionEvent e = null;
            removeArtistButtonActionPerformed(e);
        }
    }//GEN-LAST:event_artistTableMouseClicked

    private void availArtistTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_availArtistTableMouseClicked
        if(evt.getClickCount()==2){
            ActionEvent e = null;
            addArtistButtonActionPerformed(e);
        }
    }//GEN-LAST:event_availArtistTableMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addArtistButton;
    private java.util.List<pojos.Artist> artistList;
    private java.util.List<pojos.Artist> artistList1;
    private javax.swing.JLabel artistListLabel;
    private javax.persistence.Query artistQuery;
    private javax.persistence.Query artistQuery1;
    private javax.swing.JTable artistTable;
    private javax.swing.JLabel availArtistLabel;
    private javax.swing.JList availArtistTable;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton changeButton;
    private javax.swing.JButton deleteButton1;
    private javax.swing.JButton exitButton;
    private com.toedter.calendar.JDateChooser formationDateDateChooser;
    private javax.swing.JLabel formationDateLabel;
    private javax.swing.JLabel groupNameLabel;
    private javax.swing.JTextField groupNameTextField;
    private javax.swing.JTable groupTable;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane4;
    private java.util.List<pojos.Musicgroup> musicgroupList;
    private javax.persistence.Query musicgroupQuery;
    private javax.swing.JButton newButton;
    private javax.swing.JButton removeArtistButton;
    private javax.swing.JButton saveButton;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
